//
//  EmoticonCell.swift
//  EmoticonKeyboard
//
//  Created by liii on 16/8/14.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit
import SnapKit

// 通知: No.1, 定义通知
let EmoticonButtonClickedNotification = "EmoticonButtonClickedNotification"

class EmoticonCell: UICollectionViewCell {
    
    // 表情按钮
    var EmoticonButtons = [EmoticonButton]()
    
    // 表情数据
    var emoticons: [Emoticon]? {
        didSet {
            // 遍历模型, 拿到对应索引的对应值
            for (i, emotion) in emoticons!.enumerate() {
                // 拿到对应按钮
                let btn = EmoticonButtons[i]
                // 传递到自定义按钮的, 模型中
                btn.emoticon = emotion
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        // 每行7个按钮, 每页3行
        let ColCount = 7
        let RowCount = 3
        
        let leftMargin: CGFloat = 5
        let bottomMargin: CGFloat = 20
        
        let itemW = (self.bounds.width - 2 * leftMargin) / CGFloat(ColCount)
        let itemH = (self.bounds.height - bottomMargin) / CGFloat(RowCount)
        
        for i in 0 ..< emojiCountPerPage {
            
            let btn = EmoticonButton()
            // 设置Emoji表情的大小, 因为是字符串, 以文本的形式存在, 所以设置字体
            btn.titleLabel?.font = UIFont.systemFontOfSize(32)
            
            // i 所在的行和列
            let iCol  = i % ColCount
            let iRow = i / ColCount
            
            let itemX = CGFloat(iCol) * itemW + leftMargin
            let itemY = CGFloat(iRow) * itemH
            
            btn.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
            btn.addTarget(self, action: "EmotionButtonDidClick:", forControlEvents: .TouchUpInside)
            
            // 添加到Cell
            contentView.addSubview(btn)
            // 保存到一个数组
            EmoticonButtons.append(btn)
        }
    }
    
    @objc private func EmotionButtonDidClick(btn: EmoticonButton) {
        
        // 通知: No.2, 发出通知
        // 发出通知, 把表情数据传递给控制器, 用来更新textView
        NSNotificationCenter.defaultCenter().postNotificationName(EmoticonButtonClickedNotification, object: btn.emoticon)
    }
    
}
